package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.LoginService;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.ActionItem;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.SlideView;
import com.pocketsweet.ui.uilib.SlideView.OnSlideListener;
import com.pocketsweet.ui.uilib.TitlePopup;
import com.pocketsweet.ui.uilib.TitlePopup.OnItemOnClickListener;
import com.pocketsweet.ui.uilib.adapter.OnLineTestLoverAdapter;
import com.pocketsweet.ui.uilib.adapter.OnLineTestLoverAdapter.ViewHolder;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_newonline)
public class OnlineTestLoverActivity extends Activity implements
		OnRefreshListener, OnLoadListener, OnItemClickListener, OnTouchListener {

	private AutoListView dropDownListView = null;
	private static OnLineTestLoverAdapter onLineListAdapter;
	public static List<MLUser> userList = new ArrayList<MLUser>();
	private static final int MORE_DATA_MAX_COUNT = 50; // 每页20个对象
	private static final int BEGIN_TO_LOADING = -1;
	private int skipDataCount = 0; // 忽略前N个对象
	private boolean isUpdateList = false; // 是否刷新列表
	private LinearLayout linBlank;
	private static boolean isSlide = false;
	final int RIGHT = 0;
	final int LEFT = 1;
	private static TitlePopup titlePopup;
	private MLApplication mlApplication;

	// 双击
	private int count = 0;
	private int firClick = 0;
	private int secClick = 0;

	private boolean isClicked = false;
	private static final String ACTION_CHOOSE_CHANGE = "action_choose_change";

	private MLUser mlUser;
	private ViewHolder userHolder;
	private static OnSlideListener slideLister;
	private SlideView mLastSlideViewWithStatusOn;
	int tempSex;
	private LoginService loginService;

	private LinearLayout llRandomCall;
	private HeaderLayout mainHeader;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ACTION_CHOOSE_CHANGE)) {
				if (MLApplication.chooseSex == 0) {
					mainHeader.setRightImg(R.drawable.icon_sex_all);
				} else if (MLApplication.chooseSex == 1) {
					mainHeader.setRightImg(R.drawable.icon_sex_man);
				} else if (MLApplication.chooseSex == 2) {
					mainHeader.setRightImg(R.drawable.icon_sex_female);
				}
				if (userList != null) {
					userList.clear();
				}
				onLineListAdapter.notifyDataSetChanged();
				dropDownListView.setAdapter(onLineListAdapter);
				getUserList(BEGIN_TO_LOADING);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlApplication = MLApplication.getInstance();
		setHeaderFunction();
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		dropDownListView = (AutoListView) findViewById(R.id.testLoverListview);
		linBlank = (LinearLayout) findViewById(R.id.linBlank);
		loginService = new LoginService(OnlineTestLoverActivity.this);
		onLineListAdapter = new OnLineTestLoverAdapter(this, userList);
		dropDownListView.setAdapter(onLineListAdapter);
		onLineListAdapter.notifyDataSetChanged();
		dropDownListView.setPageSize(MORE_DATA_MAX_COUNT);
		dropDownListView.setOnRefreshListener(this);
		dropDownListView.setOnLoadListener(this);
		dropDownListView.setOnItemClickListener(this);
		// dropDownListView.setOnScrollListener(lvScrollListener);
		getUserList(BEGIN_TO_LOADING);// 首次进入app，加载数据
		// MLContext.deleteAll(); // 清空sharepreference
		slideLister = new OnSlideListener() { // 如果当前存在已经打开的SlideView，那么将其关闭

			@Override
			public void onSlide(View view, int status) {
				if (mLastSlideViewWithStatusOn != null
						&& mLastSlideViewWithStatusOn != view) {
					mLastSlideViewWithStatusOn.shrink();
				}

				if (status == SLIDE_STATUS_ON) {
					mLastSlideViewWithStatusOn = (SlideView) view;
				}

			}
		};

		// 情侣电话
		// llRandomCall = (LinearLayout)
		// getView().findViewById(R.id.llRandomCall);
		// llRandomCall.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (isClicked == true) {
		// return;
		// }
		// isClicked = true;
		// Intent intent = new Intent(getActivity(),
		// RandomCallMatchingActivity.class);
		// getActivity().startActivity(intent);
		// }
		// });
	}

	public void setHeaderFunction() {
		mainHeader = (HeaderLayout) findViewById(R.id.testLoverHeader);
		mainHeader.init(HeaderStyle.IMG_TITLE_IMG);
		mainHeader.setMiddleText("实习恋人");
		mainHeader.setOnTouchListener(this);
		if (MLApplication.chooseSex == -1) {
			if (UserService.getCurrentUser().getGender() == 1) {
				MLApplication.chooseSex = 2;
				mainHeader.setRightImg(R.drawable.icon_sex_female);
			} else {
				MLApplication.chooseSex = 1;
				mainHeader.setRightImg(R.drawable.icon_sex_man);
			}
		} else {
			if (MLApplication.chooseSex == 2) {
				mainHeader.setRightImg(R.drawable.icon_sex_female);
			} else if (MLApplication.chooseSex == 1) {
				MLApplication.chooseSex = 1;
				mainHeader.setRightImg(R.drawable.icon_sex_man);
			}else if(MLApplication.chooseSex == 0){
				mainHeader.setRightImg(R.drawable.icon_sex_all);
			}
		}
		mainHeader
				.setRighttContainerClickListener(new onRightContainerListener() {
					@Override
					public void onClick() {
						// 实例化标题栏弹窗
						// 实例化标题栏弹窗
						titlePopup = new TitlePopup(Main.getInstance(),
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT);
						// 给标题栏弹窗添加子类
						titlePopup.addAction(new ActionItem(Main.getInstance(),
								"  全部", R.drawable.icon_sex_all));
						titlePopup.addAction(new ActionItem(Main.getInstance(),
								"  男生", R.drawable.icon_sex_man));
						titlePopup.addAction(new ActionItem(Main.getInstance(),
								"  女生", R.drawable.icon_sex_female));
						titlePopup
								.setItemOnClickListener(new OnItemOnClickListener() {

									@Override
									public void onItemClick(ActionItem item,
											int position) {
										switch (position) {
										case 0:
											tempSex = 0;
											break;
										case 1:
											tempSex = 1;
											break;
										case 2:
											tempSex = 2;
											break;
										default:
											break;
										}
										if (MLApplication.chooseSex != tempSex) {
											MLApplication.chooseSex = tempSex;
											Intent intent2 = new Intent();
											intent2.setAction(Main.ACTION_CHOOSE_CHANGE);
											Main.getInstance().sendBroadcast(
													intent2);
										}

									}
								});
						titlePopup.show(mainHeader.llRightContainer);
						// getIvRightImg());
						// Intent screenDailog = new Intent(mContext,
						// DialogScreen.class);
						// screenDailog.putExtra("choosedSex", Main.choosedSex);
						// screenDailog.putExtra("choosedCity",
						// Main.choosedCity);
						// screenDailog.putExtra("choosedType",
						// Main.choosedType);
						// mContext.startActivity(screenDailog);
					}
				});
		mainHeader.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				OnlineTestLoverActivity.this.finish();
			}
		});
	}

	@Override
	public void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_CHOOSE_CHANGE);
		registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {
		isClicked = false;
		super.onResume();
		if (Main.needRefresh) {
			getUserList(AutoListView.REFRESH);
		}
		if (userHolder != null) {
			userHolder.update(mlUser);
			userHolder = null;
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	/*
	 * 请求最近在线对象
	 */
	private void getUserList(final int what) {
		userList = mlApplication.getTestUserList(); //
		// 从Application里获取userList，若为空则获取网络数据
		if (what != BEGIN_TO_LOADING) {
			isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新

		} else {
			dropDownListView.setRefreshData(); // 初始化显示loading动态图片
		}
		if (userList == null || userList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
			AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
			skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
			if (what != AutoListView.LOAD) {
				skipDataCount = 0; // 刷新时不用忽略前面对象
				AVAnalytics.onEvent(this, "实习恋人页面刷新");
			}
			// if (Main.choosedCity == 1
			// && UserService.getCurrentUser().getLocationCity() != null) {
			// query.whereEqualTo(MLUser.LOCATION_CITY, UserService
			// .getCurrentUser().getLocationCity());//同城筛选
			//
			// }
			if (MLApplication.chooseSex != 0 ) {
				query.whereEqualTo(MLUser.GENDER, MLApplication.chooseSex);
			}
			query.whereEqualTo(MLUser.TYPE, C.USER_TYPE_NORMAL);
			linBlank.setVisibility(View.GONE);
			query.setSkip(skipDataCount); // 忽略前N个
			query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
			query.orderByDescending(MLUser.LASTLOGIN);
			query.whereEqualTo("isUserInited", 1); // 只显示 认证完成的用户
			// query.whereNotEqualTo("objectId", UserService.getCurrentUser()
			// .getObjectId());// 不用显示自己
			query.findInBackground(new FindCallback<MLUser>() {
				@Override
				public void done(List<MLUser> users, AVException e) {
					// loading.dismiss();
					// 取出参与的人
					// Log.e("==user==", users.toString() + " ");
					if (e == null) {
						if (users.size() != 0) {
							switch (what) {
							case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
								userList = users;
								dropDownListView.onRefreshComplete();
								loginService.setLastLoginDate();
								// onLineListAdapter.setDatas(userList);
								break;
							case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
								dropDownListView.onLoadComplete();
								userList.addAll(users);
								break;
							case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
								userList = users;
								dropDownListView.onRefreshComplete();
								loginService.setLastLoginDate();
								// onLineListAdapter.setDatas(userList);
								break;
							}
							mlApplication.setTestUserList(userList);
							linBlank.setVisibility(View.GONE);
							dropDownListView.setResultSize(userList.size());
							onLineListAdapter.setDatas(userList);
							onLineListAdapter.notifyDataSetChanged();
							isUpdateList = false; // 刷新完毕，设为false
						} else if (users.size() == 0) {
							if (what != AutoListView.LOAD) {
								ToolKits.toast(OnlineTestLoverActivity.this,
										"无搜索结果");
							}
							dropDownListView.setNoData();
						}
					} else {
						// error ，继续重新获取
						// Log.e("==nothing", "error:" + e.getMessage());
						linBlank.setVisibility(View.VISIBLE);
						getUserList(BEGIN_TO_LOADING);
					}
				}
			});
		} else {
			// Log.e("==refresh", "begin to load false ");
			dropDownListView.setResultSize(userList.size());
			onLineListAdapter.setDatas(userList);
			onLineListAdapter.notifyDataSetChanged();
			dropDownListView.setSelectionFromTop(MLApplication.mPosition,
					MLApplication.lvChildTop); // listMessage 是listview ，

		}
	}

	@Override
	public void onLoad() {
		getUserList(AutoListView.LOAD);
	}

	@Override
	public void onRefresh() {
		getUserList(AutoListView.REFRESH);
		dropDownListView.setOnRefreshListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// if (position == 1) {

		// if (isClicked == false) {
		// isClicked = true;
		// Intent intent = new Intent(this,
		// RandomCallMatchingActivity.class);
		// startActivity(intent);
		// String sex = null;
		// if (UserService.getCurrentUser().getType() == 1) {
		// sex = "男";
		// } else {
		// sex = "女";
		// }
		// AVAnalytics.onEvent(this, "情侣电话", sex);

		// }
		// } else {
		// mlUser = (MLUser) onLineListAdapter.getItem(position - 2);
		if (position - 1 < 0 || onLineListAdapter.getCount() <= 0) {
			return;
		}
		mlUser = (MLUser) onLineListAdapter.getItem(position - 1);
		if (mlUser.getType() == C.USER_TYPE_NORMAL) {
			isSlide = false;
		}
		if (isSlide == true) { // 如果正在滑动，不触发点击事件
			return;
		}
		userHolder = onLineListAdapter.new ViewHolder(view);

		String selectedUserId = ((MLUser) onLineListAdapter
				.getItem(position - 1)).getObjectId();
		// String selectedUserId = ((MLUser) onLineListAdapter
		// .getItem(position - 2)).getObjectId();

		Intent intent = new Intent(this, Profile.class);
		// Log.e("String", selectedUserId + "  " + likeCount);
		intent.putExtra("userId", selectedUserId);
		intent.putExtra("nickname", mlUser.getNickname());
		startActivity(intent);

		// }

	}

	// private OnScrollListener lvScrollListener = new OnScrollListener() {
	//
	// @Override
	// public void onScrollStateChanged(AbsListView view, int scrollState) {
	// // TODO Auto-generated method stub
	// // 不滚动时保存当前滚动到的位置
	// if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
	// MLApplication.mPosition = dropDownListView.getFirstVisiblePosition();
	// View v = dropDownListView.getChildAt(0);
	// MLApplication.lvChildTop = (v == null) ? 0 : v.getTop();
	// }
	// }
	//
	// @Override
	// public void onScroll(AbsListView view, int firstVisibleItem, int
	// visibleItemCount, int totalItemCount) {
	// // TODO Auto-generated method stub
	//
	// }
	// };

	@Override
	public boolean onTouch(View arg0, MotionEvent event) {
		if (MotionEvent.ACTION_DOWN == event.getAction()) {
			if ((int) System.currentTimeMillis() - firClick > 1000) {
				count = 0;
				firClick = 0;
				secClick = 0;
			}
			count++;
			if (count == 1) {
				firClick = (int) System.currentTimeMillis();
			} else if (count == 2) {
				secClick = (int) System.currentTimeMillis();
				if (secClick - firClick < 1000) {
					// 双击事件
					dropDownListView.setSelection(0);
					// dropDownListView.scrollTo(0, 0);
				} else {
				}
				count = 0;
				firClick = 0;
				secClick = 0;
			}
		}
		return true;
	}
}